﻿using HookupAppForm.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static HookupAppForm.Dto.ResultDto;

namespace HookupAppForm.Draw
{
    public class Do_Paidian
    {
        private static readonly string apiSubmain = "api/services/app/HKP_Submain/";
        private static readonly string apiTakeOff = "api/services/app/HKP_TakeOff/";
        private static readonly string apiHDC = "api/services/app/HKP_HDC/";
        private static readonly string apiSysReq = "api/services/app/HKP_ToolSysReq/";

        private static APIClient Client;
        private static HKP_BlockDto Block { get; set; }
        private static HKP_ToolDto Tool { get; set; }
        private static decimal sys_flowoper_uniq = 0;

        public static bool paidian(APIClient _client, HKP_TakeoffDto takeoff, HKP_BlockDto _block, HKP_ToolDto _tool, string toolSysReqId)
        {
            Client = _client;
            HKP_ToolSysReqDto toolSysReq = GetObject<HKP_ToolSysReqDto>(toolSysReqId, apiSysReq, "Get");
            // 1是这个takeoff点是启用状态，
            // 2是这个点要没有被派过点，
            // 3是takeoff点的尺寸要大于机台上面接点的尺寸，
            // 4是在选择的范围内
            if (!takeoff.Enabled)
            {
                Utils.SysMsg("该接点已被禁用！");
                return false;
            }
            //修改机台的接点未已使用
            ErrorObject upPd = UsedToolSeq(toolSysReq, true);
            if (upPd != null)
            {
                Utils.SysMsg(upPd.error?.message);
                return false;
            }
            //接点如果Used==false，说明这个接点第一次派点，扣除管道接口数量
            if (takeoff.Used != true)
            {
                if (toolSysReq.SysNo == "ES")
                {
                    if (takeoff.PointType != "1")
                    {
                        double toolRongL = Utils.ToInA(toolSysReq.FlowPeak.ToString(), toolSysReq.FlowUnit);//机台负荷算出安培
                        if (toolRongL <= 0)
                        {
                            toolRongL = Utils.ToInA(toolSysReq.Power.ToString(), toolSysReq.FlowUnit);//功率算出安培
                        }
                        //电力接点算出的安培
                        takeoff.FlowPeak =Convert.ToDecimal(toolRongL);
                    }     
                }
               
                //decimal usedFl=Utils.ToInA()
                //takeoff点是第一次派点  派点成功要把管道上的接点+1
                upPd = UsedSubmainPoint(takeoff.SubmainId.ToString(), 1,takeoff.FlowPeak);
              
            }

    
            //if (takeoff.OutType != toolSysReq.OutType)
            //{
            //    Utils.SysMsg("接口类型不匹配！");
            //    return false;
            //}
            ErrorObject resp = null;
            if (toolSysReq.SysNo == "ES")
            {
                double toolRongL = Utils.ToInA(toolSysReq.FlowPeak.ToString(), toolSysReq.FlowUnit);//机台负荷算出安培
                if (toolRongL <= 0)
                {
                    toolRongL = Utils.ToInA(toolSysReq.Power.ToString(), toolSysReq.FlowUnit);//功率算出安培
                }

                if (takeoff.PointType == "1")
                {
                    int usdpoint = 1;
                    //if (toolSysReq.OutSize == "380" || toolSysReq.OutSize == "208")
                    //{
                    //    usdpoint = 3;
                    //}
                    //if (toolSysReq.OutSize == "220" || toolSysReq.OutSize == "120")
                    //{
                    //    usdpoint = 1;
                    //}
                    resp = UsedTakeOff(takeoff, Convert.ToDecimal(toolRongL), toolSysReq.SysNo, "1", toolSysReq.Name, _tool.ToolId, usdpoint);
                }
                else
                {
                    resp = UsedTakeOff(takeoff, Convert.ToDecimal(toolRongL), toolSysReq.SysNo,"0", toolSysReq.Name,_tool.ToolId,1);
                }
            }
            else
            {
                //其他系统要算横截面积，所以要重新调用一个方法
                resp = UsedTakeOffOthe(takeoff, Convert.ToDecimal(Utils.ToInMM(toolSysReq.OutSize, toolSysReq.OutSizeUnit)), toolSysReq.SysNo,"0", toolSysReq.Name, _tool.ToolId,0);
            }
            if (resp != null)
            {
                //如果修改接点失败，要把接点派点标记放开
                UsedToolSeq(toolSysReq, false);
                //要把管道的点还给管到
                UsedSubmainPoint(takeoff.SubmainId.ToString(), -1, takeoff.FlowPeak);
                //弹出提示消息
                Utils.SysMsg(resp.error?.message);
                return false;
            }

            CreateHDC(takeoff, _tool, _block, takeoff.SysName, takeoff.SubmainId.ToString(), toolSysReq);

            return true;
        }
        public static bool paidian2(APIClient _client, HKP_TakeoffDto takeoff, HKP_BlockDto _block, HKP_ToolDto _tool)
        {
            Client = _client;
            Block = _block;
            Tool = _tool;

            //string url2 = string.Format(apiTakeOff + "GetList?blockId={0}", Block.Id);
            //var result2 = Client.Get(url2);
            //ItemsDto<HKP_TakeoffDtoChk> res2 = JsonConvert.DeserializeObject<ItemsDto<HKP_TakeoffDtoChk>>(result2);
            //var res = res2.result.items.FirstOrDefault(a => a.TakeoffNo == takeoff.TakeoffNo);

            string url = string.Format(apiTakeOff + "Get?Id={0}", takeoff.Id);
            var result = Client.Get(url);
            var ress = JsonConvert.DeserializeObject<ListsDto<HKP_TakeoffDtoChk>>(result);
            var res = ress.result;

            if (res.Used)
            {
                Utils.SysMsg("该接点已被使用！");
                return false;
            }
            if (!res.Enabled)
            {
                Utils.SysMsg("该接点已被禁用！");
                return false;
            }
            var lists = new List<HKP_TakeoffDtoChk> { res };
            var sysReqArr = GetToolSysReq(Tool.ToolId);
            foreach (var item in lists)
            {
                HKP_SubmainDto submainDto = GetObject<HKP_SubmainDto>(takeoff.SubmainId.ToString(), apiSubmain, "GetById");
                item.Submain = submainDto;
            }
            List<HKP_TakeoffDtoChk> newList = new();
            bool ischk = true, ischk2 = true, ischk3 = true;
            //选取的机台的接口操作流量。
            sys_flowoper_uniq = 0;
            foreach (HKP_ToolSysReqDto sys in sysReqArr)
            {
                ischk = true; ischk2 = true; ischk3 = true;
                string reason = string.Empty;
                var obj = lists.Where(o => o.Submain.SysNo == sys.SysNo).FirstOrDefault();
                if (obj != null)
                {
                    //接点外径

                    double waijin = 0d;
                    if (!string.IsNullOrEmpty(obj.OutSize))
                        waijin = Utils.FtToInMM(obj.OutSize, obj.OutSizeUnit);

                    //机台接口外径
                    double waijinTool = Utils.FtToInMM(sys.OutSize, sys.OutSizeUnit);

                    //if (waijinTool > waijin)
                    //{
                    //    reason += "外径尺寸不相符；";
                    //    //ischk = false;
                    //    continue;
                    //}

                    if (obj.OutType != sys.OutType)
                    {
                        reason += "接口类型不相符；";
                        //ischk2 = false;
                        continue;
                    }

                    if (Utils.ConvertFlow(obj.FlowPeakOperation, obj.FlowUnit) < Utils.ConvertFlow(sys.FlowPeak, sys.FlowUnit))
                    {
                        reason += "流量大小不能超过接口操作流量峰值；";
                        //ischk3 = false;
                        continue;
                    }
                    obj.OutSizeTool = sys.OutSize + sys.OutSizeUnit;
                    obj.FlowPeakTool = sys.FlowPeak;
                    obj.FlowPeakToolUnit = sys.FlowUnit;
                    obj.OutTypeTool = sys.OutType;
                    obj.Reason = reason;
                    obj.Checked = ischk && ischk2 && ischk3;
                    obj.SysNo = sys.SysNo;
                    obj.OutSize = obj.OutSize + obj.OutSizeUnit;
                    obj.ToolSysReqId = sys.Id;
                    obj.Distence = Math.Round(Utils.GetDistance(Convert.ToInt32(obj.X), Convert.ToInt32(obj.Y), Convert.ToInt32(Tool.X), Convert.ToInt32(Tool.Y)) / 100, 2);
                    newList.Add(obj);
                    lists.Remove(obj);
                    //仅仅使用一个有效匹配即可
                    sys_flowoper_uniq = sys.FlowOper;
                    break;
                }
                else
                {
                    //HKP_TakeoffDtoChk obj2 = new();
                    //obj2.OutSizeTool = sys.OutSize;
                    //obj2.FlowPeakTool = sys.FlowPeak;
                    //obj2.OutTypeTool = sys.OutType;
                    //obj2.Reason = "暂无接点可用";
                    //obj2.SysNo = sys.SysNo;
                    //newList.Add(obj2);
                    continue;
                }
            }

            if (newList.Count == 0) return false;

            //dataGridViewM.DataSource = newList;
            //执行派点 
            //var takeoffDtos = newList;
            //takeoffDtos = takeoffDtos.Where(o => o.Checked).ToList();
            //foreach (HKP_TakeoffDtoChk item in takeoffDtos)
            //{
            //    if (item.Submain != null)
            //        CreateHDC(item, Tool, Block, item.Submain, item.ToolSysReqId);
            //}
            return true;
        }
        private static void CreateHDC(HKP_TakeoffDto takeoff, HKP_ToolDto tool, HKP_BlockDto block, string sysNo, string submainNo, HKP_ToolSysReqDto toolSysReq)
        {
            ErrorObject resp = null;
            if (resp == null)
            {
                string act = "Create";
                CreateHKP_HDCDto dto = new()
                {
                    ToolId = Guid.Parse(tool.Id),
                    Bay = block.BlockName,
                    Building = block.Building,
                    FabArea = block.BlockName,
                    Floor = block.Floor,
                    SubmainNo = submainNo,
                    SysNo = sysNo,
                    TakeoffNo = takeoff.TakeoffNo,
                    ToolSysReqId = toolSysReq.Id,
                    //文号跟着机台的送审文号走
                    SignatureNo = tool.SignatureNo,
                    //编号
                    TranNo = tool.SignatureNo

                };
                string jsons = JsonConvert.SerializeObject(dto);
                string result = Client.Post(apiHDC + act, jsons);
                Utils.ExceptionHandler(result);
                Utils.SysMsg("派点成功！");
               
            }
            else
            {
                Utils.SysMsg(resp.error?.message);
            }
        }
        /// <summary>
        /// 修改takeoff点的跟容量
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="val"></param>
        /// <param name="sysno"></param>
        /// <param name="pointtype"></param>
        /// <returns></returns>
        private static ErrorObject UsedTakeOff(HKP_TakeoffDto Item, decimal val,string sysno,string pointtype, string toolSysNo,string toolNo,int Userpoint)
        {
            ErrorObject resp = new ErrorObject();
            if (Item != null)
            {
                HKP_TakeoffDto dto = GetObject<HKP_TakeoffDto>(Item.Id.ToString(), apiTakeOff);
                dto.Used = true;
                string jsons = JsonConvert.SerializeObject(new { id = Item.Id.ToString(), usedFlow = val,sysno=sysno, PointType=pointtype, toolSysNo= toolSysNo, toolNo = toolNo, Userpoint= Userpoint,Used=true });
                string result = Client.Post(apiTakeOff + "UsedTakeOff", jsons);
                resp = Utils.ExceptionMsg(result);
            }
            return resp;
        }

        /// <summary>
        /// 修改takeoff点的尺寸，要算横截面积
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="val"></param>
        /// <param name="sysno"></param>
        /// <param name="pointtype"></param>
        /// <returns></returns>
        private static ErrorObject UsedTakeOffOthe(HKP_TakeoffDto Item, decimal val, string sysno, string pointtype, string toolSysNo, string toolNo, int Userpoint)
        {
            ErrorObject resp = new ErrorObject();
            if (Item != null)
            {
                HKP_TakeoffDto dto = GetObject<HKP_TakeoffDto>(Item.Id.ToString(), apiTakeOff);
                dto.Used = true;
                double r = Convert.ToDouble(val / 2);
                double shiyongMj = r * r * 3.14;

                string jsons = JsonConvert.SerializeObject(new { id = Item.Id.ToString(), usedFlow = shiyongMj, sysno = sysno, PointType = pointtype, toolSysNo = toolSysNo, toolNo = toolNo, Userpoint = Userpoint, Used = true });
                string result = Client.Post(apiTakeOff + "UsedTakeOff", jsons);
                resp = Utils.ExceptionMsg(result);
            }
            return resp;
        }




        /// <summary>
        /// 修改接点为已派点
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="val"></param>
        /// <param name="sysno"></param>
        /// <param name="pointtype"></param>
        /// <returns></returns>
        private static ErrorObject UsedToolSeq(HKP_ToolSysReqDto Item,bool type)
        {
            ErrorObject resp = new ErrorObject();
            if (Item != null)
            {
                //HKP_ToolSysReqDto dto = GetObject<HKP_ToolSysReqDto>(Item.Id.ToString(), apiSysReq);
                //dto.isPaiDian = type;
                //string jsons = JsonConvert.SerializeObject(new { id = Item.Id.ToString(), istype = type});
                //string result = Client.Post(apiSysReq + "UsedPaiDian", jsons);
                string result = Client.Post(apiSysReq + "UsedPaiDian?id="+Item.Id+"&istype="+type+"","");
                resp = Utils.ExceptionMsg(result);
            }
            return resp;
        }
        /// <summary>
        /// 增加管道的使用点数
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="val"></param>
        /// <param name="sysno"></param>
        /// <param name="pointtype"></param>
        /// <returns></returns>
        private static ErrorObject UsedSubmainPoint(string  id, int usedpoing,decimal usedFlow)
        {
            ErrorObject resp = new ErrorObject();
            if (!string.IsNullOrEmpty(id))
            {
                //HKP_ToolSysReqDto dto = GetObject<HKP_ToolSysReqDto>(Item.Id.ToString(), apiSysReq);
                //dto.isPaiDian = type;
                //string jsons = JsonConvert.SerializeObject(new { id = Item.Id.ToString(), istype = type});
                //string result = Client.Post(apiSysReq + "UsedPaiDian", jsons);
                string result = Client.Put(apiSubmain + "upDateUsedflow?id=" + id + "&x=" + usedpoing + "&usedflow="+ usedFlow + "", "");
                resp = Utils.ExceptionMsg(result);
            }
            return resp;
        }

        private static HKP_ToolSysReqDto[] GetToolSysReq(string toolId)
        {
            string url = string.Format(apiSysReq + "GetList?toolId={0}", toolId);
            var result = Client.Get(url);
            ItemsDto<HKP_ToolSysReqDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolSysReqDto>>(result);
            return dto.result.items;
        }
        private static T GetObject<T>(string id, string api, string act = "Get")
        {
            string result = Client.Get(api + act + "?Id=" + id.ToString());
            var resp = Utils.SuccessHandler(result);
            return JsonConvert.DeserializeObject<T>(resp.ToString());
        }
    }
}
